package com.zhouyu.mybatis.spring;

import com.zhouyu.service.UserMybatisService;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;

import java.io.IOException;
import java.util.Map;

/**
 * @author mimao funfind@yeah.net
 * @date ${{
 */
public class WangImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {


		//扫描路径---importingClassMetadata代表拿到了所有的注解信息
		// 拿到WangMapperScan，注解上面的路径信息，
		Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(WangMapperScan.class.getName());
		String path = (String)annotationAttributes.get("value");
		System.out.println(path);

		//实现自己的scan
		WangBeanDefinitonScanner wangBeandefinitonScanner = new WangBeanDefinitonScanner(registry);
		//这里有一个过滤器，spring原生回过滤非Component的注解数据，重写之后我们就全部为true，直接都生成bean
		wangBeandefinitonScanner.addExcludeFilter(new TypeFilter() {
			@Override
			public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
				return true;
			}
		});

		wangBeandefinitonScanner.scan(path);


		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
		beanDefinition.setBeanClass(WangFactoryBean.class);
		beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(UserMybatisService.class);
		registry.registerBeanDefinition("userMapper",beanDefinition);    //userMapper----UserMapper代理对象

	}
}
